﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;

//using System.Windows.Forms;

namespace Utilities
{
    public class DbManager
    {
        public class DBConnection : IDisposable
        {
            private OleDbConnection m_Conn = null;
            private OleDbDataReader DataReader;

            public DBConnection(string ConStr)
            {
                m_Conn = new OleDbConnection();
                m_Conn.ConnectionString = ConStr;
            }

            public void Dispose()
            {
                 try{
                     if (DataReader != null)
                        DataReader.Dispose();

                     if (m_Conn != null)
                        m_Conn.Dispose();
                 }
                 catch(Exception)
                 {}
                 finally{
                     //remove myStream from the GC finalize queue
                     if (DataReader != null)
                        GC.SuppressFinalize(DataReader);

                     if (m_Conn != null)
                        GC.SuppressFinalize(m_Conn);
                 }
            }

            public void ExecuteNonQuery(string command, OleDbParameter[] dbCollection)
            {
                 if (m_Conn.State != System.Data.ConnectionState.Open)
                     m_Conn.Open();

                 OleDbCommand cmd = new OleDbCommand(command, m_Conn);

                 if (dbCollection != null)
                     foreach (OleDbParameter odb in dbCollection)
                         cmd.Parameters.Add(odb);

                 cmd.ExecuteNonQuery();
            }

            public OleDbDataReader ExecuteQuery(string command, OleDbParameter[] dbCollection)
             {
                 if (m_Conn.State != System.Data.ConnectionState.Open)
                     m_Conn.Open();

                 OleDbCommand cmd = new OleDbCommand(command, m_Conn);

                 if (dbCollection != null)
                     foreach (OleDbParameter odb in dbCollection)
                         cmd.Parameters.Add(odb);

                 DataReader = cmd.ExecuteReader();
                 return DataReader;
             }
        }
       
        //private OleDbConnection m_Conn = null;
        public DBConnection Connection;
        private string m_connectionStr;

        public DbManager(string dbPath)
        {
            m_connectionStr = @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data source=" + dbPath;
        }

        public DBConnection CreateConnection()
        {
            return new DBConnection(m_connectionStr);
        }
    }
}
